package com.spdzen.service.impl;

import com.spdzen.model.SysUserRole;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.spdzen.mapper.SysUserRoleMapper;
import com.spdzen.service.SysUserRoleService;
import com.spdzen.support.SimpleServiceImpl;
import com.spdzen.support.shiro.ShiroDynamicAuthorization;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户角色关联 服务实现类
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends SimpleServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

	@Override
	public int deleteByUser(Long sysUserId) {
		SysUserRole record = new SysUserRole();
		record.setSysUserId(sysUserId);

		Wrapper<SysUserRole> wrapper = new EntityWrapper<>(record);
		return baseMapper.delete(wrapper);
	}

	@Override
	public List<SysUserRole> selectByUser(Long sysUserId) {
		SysUserRole record = new SysUserRole();
		record.setSysUserId(sysUserId);

		Wrapper<SysUserRole> wrapper = new EntityWrapper<>(record);
		return baseMapper.selectList(wrapper);
	}

	@Override
	@Transactional(rollbackFor = { Exception.class })
	@ShiroDynamicAuthorization
	public void bindRoles(Long sysUserId, List<Long> roleIds) throws Exception {
		deleteByUser(sysUserId);

		for (Long rid : roleIds) {
			SysUserRole record = new SysUserRole();
			record.setSysUserId(sysUserId);
			record.setSysRoleId(rid);

			baseMapper.insert(record);
		}
	}

}
